import React from 'react';
import { history } from 'umi'
import { PageContainer } from '@/molecules';
import authHelper from '@/utils/auth/helper';
import Channel from './Channel';
import Email from './Email';
import Field from './Field';
import Tag from './Tag';
import Interview from './Interview';
import NoticeTemplate from './NoticeTemplate';
import Employed from './Employed';
import Talent from './Talent';

const { checkCode } = authHelper;

const tabList = [
    {
        key: '1',
        tab: '渠道设置',
        code: 'office:recruitment:setting:channel',
        component: <Channel />
    },
    {
        key: '2',
        tab: '邮箱设置',
        code: 'office:recruitment:setting:email',
        component: <Email />
    },
    {
        key: '3',
        tab: '字段设置',
        code: 'office:recruitment:setting:field',
        component: <Field />
    },
    {
        key: '4',
        tab: '标签管理',
        code: 'office:recruitment:setting:tag',
        component: <Tag />
    },
    {
        key: '5',
        tab: '面试设置',
        code: 'office:recruitment:setting:interview',
        component: <Interview />
    },
    // 录用设置属后来添加，原来其他key不做调整，往上添加
    {
        key: '8',
        tab: '录用设置',
        code: 'office:recruitment:setting:employed',
        component: <Employed />
    },
    {
        key: '6',
        tab: '通知设置',
        code: 'office:recruitment:setting:notice',
        component: <NoticeTemplate />
    },
    {
        key: '7',
        tab: '人才设置',
        code: 'office:recruitment:setting:talent',
        component: <Talent />
    }
];

const Setting = ({ location }) => {
    const { query } = location;
    const [activeKey, setActiveKey] = React.useState(query?.activeKey || '1');
    const [savedQuery, setSavedQuery] = React.useState(null);

    const handleTabChange = key => {
        setActiveKey(key);
        history.push({ query: { ...savedQuery?.[key], activeKey: key } });
    };

    React.useEffect(() => {
        const key = query?.activeKey || '1';
        setActiveKey(key);
        setSavedQuery({
            ...savedQuery,
            [key]: query
        });
    }, [query]);

    const filterList = tabList.filter(item => checkCode(item.code)) || [];

    React.useEffect(() => {
        if (filterList && filterList.length > 0) {
            if (!filterList.find(item => item.key === activeKey)) {
                setActiveKey(filterList[0]?.key || '');
            }
        }
    }, [JSON.stringify(filterList)]);

    return (
        <PageContainer tabList={filterList} activeTabKey={activeKey} onTabChange={handleTabChange}>
            {filterList?.find(item => item.key === activeKey)?.component}
        </PageContainer>
    );
};

export default Setting;
